/**
 * Created by zzmhot on 2017/3/23.
 *
 * 路由Map
 *
 * @author: zzmhot
 * @github: https://github.com/zzmhot
 * @email: zzmhot@163.com
 * @Date: 2017/3/23 18:30
 * @Copyright(©) 2017 by zzmhot.
 *
 */

import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import viewPageComponent from '../pages/App'

//home
import homeComponent from '../pages/home'
//404
import noPageComponent from '../pages/error/404'

import loginComponent from '../pages/user/login'

import productComponent from '../pages/product'

import productAddComponent from '../pages/product/add'
import {cookieStorage} from 'common/storage'

Vue.use(VueRouter)

//使用AMD方式加载
const routes = [
  {
    path: '/404',
    name: 'notPage',
    component: noPageComponent
  },
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/user/login',
    name: 'login',
    component: loginComponent
  },
  {
    path: '/',
    redirect: '/home',
    component: viewPageComponent,
    children: [
      {
        path: '/home',
        name: 'home',
        component: homeComponent,
        meta: {
          title: '主页',
          auth: true
        }
      },

      //商品相关
      {
        path: '/product/list',
        name: 'product',
        component: productComponent,
        meta: {
          title: '商品',
          auth: true
        }
      },

      {
        path: '/product/add',
        name: 'productAdd',
        component: productAddComponent,
        meta: {
          title: '添加',
          auth: true
        }
      },

    ]
  }
]

const router = new VueRouter({
  routes,
  mode: 'hash', //default: hash ,history
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return {x: 0, y: 0}
    }
  }
})

//全局路由配置
//路由开始之前的操作
router.beforeEach((to, from, next) => {
  NProgress.done().start()
  let toName = to.name
  // let fromName = from.name

  //判断cookie里面是否有token
  let is_login = store.state.user_info.login

  if (!is_login && toName !== 'login') {
    next({
      name: 'login'
    })
  } else {
    if (is_login && toName === 'login') {
      next({
        path: '/'
      })
    } else {
      next()
    }
  }
})

//路由完成之后的操作
router.afterEach(route => {
  NProgress.done()
})

export default router
